package com.android.manghe.index.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.android.base.tools.DisplayUtil;
import com.android.base.tools.Glide.GlideHelper;
import com.android.base.tools.ScreenUtil;
import com.android.manghe.R;
import com.android.manghe.box.model.BoxPrizeModel;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.coupon.model.CouponBannerRes;
import com.android.manghe.index.view.AutoScrollRecyclerView;
import com.android.manghe.market.activity.OpenBoxHistoryActivity;
import com.tmall.ultraviewpager.UltraViewPager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 公告和中间广告
 */
public class NoticeAdapter extends DelegateAdapter.Adapter<NoticeAdapter.NoticeViewHolder> {

    private Context mContext;
    private List<BoxPrizeModel.DataBean.ListBean> mNoticeList = new ArrayList<>();
    private List<CouponBannerRes> mBannerList = new ArrayList<>();
    private String[] noticeItemHtmlArr;
    private int itemSize;
    private NoticeViewHolder mNoticeViewHolder;
    private LinearSmoothScroller mScroller;
    private Disposable mAutoTask;

    public NoticeAdapter(Context context) {
        mContext = context;
        noticeItemHtmlArr = new String[]{};
        itemSize = (ScreenUtil.getScreenWidth(mContext) - DisplayUtil.dip2px(mContext, 44)) / 4;
        mScroller = new LinearSmoothScroller(mContext) {
            @Override
            protected int getHorizontalSnapPreference() {
                return LinearSmoothScroller.SNAP_TO_START;
            }

            @Override
            protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                return 3f / displayMetrics.density;
            }
        };

    }

    public void updateData(List<BoxPrizeModel.DataBean.ListBean> noticeList) {
        mNoticeList.clear();
        mNoticeList.addAll(noticeList);
        noticeItemHtmlArr = new String[mNoticeList.size()];
        for (int i = 0; i < mNoticeList.size(); i++) {
            BoxPrizeModel.DataBean.ListBean bean = mNoticeList.get(i);
            noticeItemHtmlArr[i] = "<strong><font color='#999999'>恭喜</font>"
                    + "<font color='#999999'>#" + bean.nickname + "#</font>"
                    + "<font color='#e84e40'>" + bean.buy_way + "</font>"
                    + "<font color='#999999'>获得</font>"
                    + "<font color='#999999'>" + bean.goods_name + "</font>"
                    + "</strong>";
        }
        notifyDataSetChanged();
    }

    public void updateBanner(List<CouponBannerRes> bannerList) {
        mBannerList.clear();
        if (bannerList != null && bannerList.size() != 0) {
            mBannerList.addAll(bannerList);
        }
        notifyDataSetChanged();
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return new LinearLayoutHelper();
    }


    @Override
    public int getItemViewType(int position) {
        return 2;
    }

    public void stopSlide() {
        if (mNoticeViewHolder != null) {
            mNoticeViewHolder.recyclerView.stop();
        }

    }

    @NonNull
    @Override
    public NoticeViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new NoticeViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_ad_notice, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NoticeViewHolder noticeViewHolder, int i) {
        this.mNoticeViewHolder = noticeViewHolder;
        noticeViewHolder.ultraViewPager.setAdapter(new NoticeAdapter.UltraPagerAdapter());
        if (noticeItemHtmlArr.length > 0) {
            noticeViewHolder.ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.VERTICAL);
            noticeViewHolder.ultraViewPager.setInfiniteLoop(true);
            noticeViewHolder.ultraViewPager.setAutoScroll(2000);
        } else {
            noticeViewHolder.ultraViewPager.setInfiniteLoop(false);
        }

        //最新的开箱纪录
        LinearLayoutManager boxAllLinearLayoutManager = new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false);
        noticeViewHolder.recyclerView.setLayoutManager(boxAllLinearLayoutManager);

        noticeViewHolder.recyclerView.setAdapter(new newBoxOpenAdapter(mContext, mNoticeList, itemSize));
        noticeViewHolder.tvFindAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击跳转到最新开箱
                Intent intent = new Intent(mContext, OpenBoxHistoryActivity.class);
                mContext.startActivity(intent);
            }
        });

        startAuto(noticeViewHolder.recyclerView);

        //下面的广告牌
        noticeViewHolder.ultraViewPagerBanner.setVisibility(mBannerList != null && mBannerList.size() != 0 ? View.VISIBLE : View.GONE);
        noticeViewHolder.ultraViewPagerBanner.setAdapter(new UltraPagerAdapterBanner());
        if (mBannerList.size() > 1) {
            noticeViewHolder.ultraViewPagerBanner.setAutoScroll(5000);
        } else {
            noticeViewHolder.ultraViewPagerBanner.disableIndicator();
            noticeViewHolder.ultraViewPagerBanner.setInfiniteLoop(false);
        }

    }

    private void startAuto(AutoScrollRecyclerView recyclerView){
        if(mAutoTask!=null&&!mAutoTask.isDisposed()){
            mAutoTask.dispose();
        }

        mAutoTask= Observable.interval(0,2100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        //滑到指定的item
                        mScroller.setTargetPosition(aLong.intValue());
                        recyclerView.getLayoutManager().startSmoothScroll(mScroller);

                    }
                });
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    class NoticeViewHolder extends RecyclerView.ViewHolder {
        public UltraViewPager ultraViewPager, ultraViewPagerBanner;
        public View layoutNotice;
        public View viewPagerZheZhao;
        private AutoScrollRecyclerView recyclerView;
        private TextView tvFindAll;


        public NoticeViewHolder(View itemView) {
            super(itemView);
            ultraViewPager = itemView.findViewById(R.id.ultraViewPager);
            layoutNotice = itemView.findViewById(R.id.layoutNotice);
            //viewPagerZheZhao = itemView.findViewById(R.id.viewPagerZheZhao);
            ultraViewPagerBanner = itemView.findViewById(R.id.ultraViewPagerBanner);
            recyclerView = itemView.findViewById(R.id.id_recycler_view);
            tvFindAll = itemView.findViewById(R.id.id_tv_find_all);
        }


    }

    private class UltraPagerAdapter extends PagerAdapter {

        public UltraPagerAdapter() {

        }

        @Override
        public int getCount() {
            return noticeItemHtmlArr.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            TextView tv = (TextView) LayoutInflater.from(container.getContext()).inflate(R.layout.layout_pager_tv_item, null);
            tv.setText(Html.fromHtml(noticeItemHtmlArr[position]));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                tv.setText(Html.fromHtml(noticeItemHtmlArr[position], Html.FROM_HTML_MODE_COMPACT));
            } else {
                tv.setText(Html.fromHtml(noticeItemHtmlArr[position]));
            }
            container.addView(tv);
            return tv;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            TextView view = (TextView) object;
            container.removeView(view);
        }
    }

    private class UltraPagerAdapterBanner extends PagerAdapter {

        @Override
        public int getCount() {
            return mBannerList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            CouponBannerRes banner = mBannerList.get(position);
            ImageView imageView = (ImageView) LayoutInflater.from(container.getContext()).inflate(R.layout.layout_pager_iv_item, null);
            GlideHelper.load(mContext, banner.src, imageView);

            container.addView(imageView);
            imageView.setOnClickListener(TextUtils.isEmpty(banner.href) ? null : new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    WebViewActivity.showActivity(mContext, new WebViewParameter.WebParameterBuilder()
                            .setUrl(banner.href)
                            .setShowProgress(true)
                            .setCanHistoryGoBackOrForward(true)
                            .setReloadable(true)
                            .setReloadType(ERefreshWebType.ClickRefresh)
                            .setCustomTitle(mContext.getString(R.string.app_name))
                            .build());
                }
            });
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView view = (ImageView) object;
            container.removeView(view);
        }
    }


}
